package com.geek.novel.network

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.widget.ImageView
import com.geek.novel.utils.ImageUtil
import com.squareup.picasso.Picasso
import com.squareup.picasso.RequestCreator
import com.squareup.picasso.Transformation

/**
 * 图片下载器
 */
class ImageDownloader private constructor(val context: Context) {

    //图片的服务类
//    private var imageService: ImageService = ImageService(context)

    /**建造器模式*/
    class Builder(private val picasso: RequestCreator){
        fun resize(width: Float, height: Float): Builder{
            picasso.resize(width.toInt(), height.toInt())
            return this
        }
        fun fit(): Builder{
            picasso.fit()
            return this
        }
        fun centerCrop(): Builder{
            picasso.centerCrop()
            return this
        }
        fun error(resId: Int): Builder{
            picasso.error(resId)
            return this
        }
        fun placeholder(resId: Int): Builder{
            picasso.placeholder(resId)
            return this
        }
        fun stackBlur(context: Context, radius: Int): Builder{
            picasso.transform(object : Transformation{
                override fun transform(source: Bitmap): Bitmap {
                    return ImageUtil.setImageStackBlur(context, source, radius)
                }
                override fun key(): String {
                    return "square()"
                }
            })
            return this
        }
        fun into(imageView: ImageView){
			picasso
//				.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
//				.config(Bitmap.Config.RGB_565)
				.into(imageView)
        }
    }

    fun build(url: String): Builder{
        val picasso = Picasso.get().load(url)
        return Builder(picasso)
    }

//    private fun getPicasso(url: String, imageView: ImageView, width: Float, height: Float, errorImg: Int): RequestCreator {
//        val picasso = Picasso.get().load(url).resize(width.toInt(), height.toInt()).centerCrop()
//        if(errorImg != 0){
//            picasso.error(errorImg)
//        }
//        return picasso
//    }

    companion object{
        @SuppressLint("StaticFieldLeak")
		private var instance: ImageDownloader? = null
        fun getInstance(context: Context): ImageDownloader{
            if(instance == null){
                synchronized(ImageDownloader::class.java){
                    if(instance == null){
                        instance = ImageDownloader(context)
                    }
                }
            }
            return instance!!
        }
    }

}